package net.sf.google.talk.eclipse.views;

import java.io.File;

import net.sf.google.talk.eclipse.EclipsePlugin;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;

public class OutgoinigFileJob extends Job {

	private final String filename;

	private final OutgoingFileTransfer t;

	public OutgoinigFileJob(final String filename, final String to,
			final XMPPConnection connection) {
		super("Sending file " + filename + " to " + to);
		this.filename = filename;
		final FileTransferManager m = new FileTransferManager(connection);
		System.out.println("to: "+to);
		System.out.println("filename: "+filename);
		t = m.createOutgoingFileTransfer(to);
		System.out.println("initialized OutgoinigFileJob(\""+filename+"\", \""+to+"\")");
	}

	@Override
	protected IStatus run(final IProgressMonitor monitor) {
		System.out.println("initiating transfer");
		try {
			monitor.beginTask("Sending file", (int) t.getFileSize());
			t.sendFile(new File(filename), "File comment");

			while (!t.isDone()) {
				if (monitor.isCanceled()) {
					t.cancel();
				}
			}
			monitor.done();
		} catch (XMPPException e) {
			System.out.println("Error sending file!");
			e.printStackTrace();
			return new Status(Status.ERROR, EclipsePlugin.ID, Status.ERROR,
					"Error sending file " + filename, e);
		}

		return Status.OK_STATUS;
	}

}
